<template>
  <div class="login-form">
    <el-form
      :model="form"
      class="form"
      ref="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item style="width: 500px" label="用户名" prop="username">
        <el-input
          v-model.trim="form.username"
          type="text"
          auto-complete="off"
        ></el-input>
      </el-form-item>
      <el-form-item style="width: 500px" label="密码" prop="password">
        <el-input
          v-model.trim="form.password"
          type="password"
          auto-complete="off"
        ></el-input>
      </el-form-item>
      <el-form-item style="width: 500px">
        <el-checkbox v-model="form.remember">记住密码</el-checkbox>
      </el-form-item>
      <el-form-item style="width: 500px">
        <el-button type="primary" @click="submitForm">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import cookie from "vue-cookie";

export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
        remember: false,
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  mounted() {
    // 如果有记住密码的cookie，直接填充用户名和密码
    if (cookie.get("remember")) {
      this.form.username = cookie.get("username");
      this.form.password = cookie.get("password");
      this.form.remember = true;
    }
  },
  methods: {
    submitForm() {
      let _this = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 提交登录成功
          this.axios
            .get(
              "http://localhost:48543/api/User/UserLogin?username=" +
                this.form.username +
                "&password=" +
                this.form.password
            )
            .then((res) => {
              if (res.data > 0) {
                alert("登录成功");
                localStorage.setItem("uid", res.data);
                if (_this.form.remember) {
                  cookie.set("username", _this.form.username, 7); // 保存7天
                  cookie.set("password", _this.form.password, 7);
                  cookie.set("remember", true, 7);
                } else {
                  // 删除cookie
                  cookie.delete("username");
                  cookie.delete("password");
                  cookie.delete("remember");
                }
                this.$router.push({ path: "/GoodsInfo" });
              } else {
                alert("登录失败");
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>